package samsung.sds.survey.surveyManagement.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import samsung.sds.departmentManagement.model.DepartmentEntity;
import samsung.sds.groupManagement.dao.GroupMapper;
import samsung.sds.survey.surveyManagement.dao.SurveyReleaseMapper;
import samsung.sds.survey.surveyManagement.model.SurveryCheckEntity;
import samsung.sds.survey.surveyManagement.model.SurveyEntity;
import samsung.sds.survey.surveyManagement.model.SurveyUserEntity;
import samsung.sds.survey.surveyManagement.service.SurveyManagementService;
import samsung.sds.survey.surveyManagement.service.SurveyReleaseService;
import samsung.sds.survey.surveyVote.model.SurveyResultEntity;
import samsung.sds.survey.surveyVote.service.VoteSurveyResultService;
import samsung.sds.system.common.baseQuery.AbstractBaseService;
import samsung.sds.system.common.baseQuery.BaseMapper;
import samsung.sds.system.common.model.QueryParam;

/**
 * @author tingcai.liu
 * @createDate 2016-01-15
 * 
 * 问卷发布的Service的接口的实现
 */
@Service
public class SurveyReleaseServiceImpl extends AbstractBaseService<SurveyUserEntity> implements SurveyReleaseService{
	@Autowired
	private SurveyReleaseMapper surveyReleaseMapper;
	
	@Autowired
	private GroupMapper groupMapper;
	
	@Autowired
	private SurveyManagementService surveyManagementServiceImpl;
	
	@Autowired
	private VoteSurveyResultService voteSurveyResultServiceImpl;
	
	@Override
	protected BaseMapper<SurveyUserEntity> getMapper() {
		return surveyReleaseMapper;
	}
	
    /**
     * 通过surveyId查找邀请的用户数
     *
     * @param surveyId
     * @return
     */
    public int queryUserCountBySurveyId(String surveyId) {
        return surveyReleaseMapper.selectTF_F_SURVEY_USER(surveyId);
    }

    /**
     * 通过surveyId查找已投票的用户数
     *
     * @param surveyId
     * @return
     */
    public int queryUserVotedCountBySurveyId(String surveyId) {
        return surveyReleaseMapper.selectTF_F_SURVEY_RESULT(surveyId);
    }
    
   /**
    * 初始化ztree checkbox的状态
    */	
	public List<SurveryCheckEntity> queryUserCheckbox(String surveyId) {
		List<DepartmentEntity> deptId = surveyReleaseMapper.departmentCheckList(surveyId);
		List<SurveryCheckEntity> list = new ArrayList<SurveryCheckEntity>();
		SurveyUserEntity su_temp = new SurveyUserEntity();
		int flag = 1;
		 for(int i=0;i<deptId.size();i++){
			SurveryCheckEntity a = new SurveryCheckEntity();
			String  departId = deptId.get(i).getDeptId().toString();
			
			su_temp.setSurvey_id(surveyId);
			su_temp.setDept_id(departId);
			
			int userAll = surveyReleaseMapper.queryDepartmentUsersListAll(su_temp);
			int userN = surveyReleaseMapper.queryDepartmentUsersListN(su_temp);
	        
			if(userN==userAll){
				flag = -1;
			}else if(userN<userAll){
				if(userN==0){
					flag=1;
				}else{
					flag = 0;	
				}
			} 
			
			a.setDepartId(departId);
			a.setFlag(flag);
			list.add(a);
		 }
		 
		 return list;
	}
    
	
   /**
    * 将checkbox从选中变为不选的用户从新增问卷发布用户中删除
    */    
	public int deleteDeptUser(String surveyId, String nocheckedDepartIds){
		 String[] nocheckedDepartIdArray = nocheckedDepartIds.split(",");
		 int nocheckedDepartIdLength = nocheckedDepartIdArray.length;
		 int noFlag = 0;
		 SurveyResultEntity surveyResult = null;
		 
		//查询checkbox状态从选中变为不选的用不选的用户
		  for(int i=0;i<nocheckedDepartIdArray.length;i++){
			  String nocheckedDepartId = nocheckedDepartIdArray[i];
			  SurveyUserEntity surveyUser = new SurveyUserEntity();
			  surveyUser.setDept_id(nocheckedDepartId);
			  surveyUser.setSurvey_id(surveyId);
			  
			  //删除用户对特定调查问卷的权限
			  List<SurveyUserEntity> nocheckedUsernameArray = surveyReleaseMapper.getNocheckedUser(surveyUser);
			  if(null != nocheckedUsernameArray){
			  int delUserCount = 0;
				//选择的条数，用于验证是否删除成功
				int isDelFinish = nocheckedUsernameArray.size();
				
				for(int j=0;j<nocheckedUsernameArray.size();j++) {
				   String nocheckedUsername = nocheckedUsernameArray.get(j).getUsername();

					//取到的用户名为空，跳出本次循环
					if(nocheckedUsername.equals("")) {
						isDelFinish--;
						continue;
					}
					surveyUser.setUsername(nocheckedUsername);
					int isDel = this.deleteEntity(surveyUser);
					
					//删除该用户的对此调查问卷的调查结果
					surveyResult = new SurveyResultEntity();
					surveyResult.setUsername(nocheckedUsername);
					surveyResult.setSurveyId(new String(surveyId));
					
					//删除用户的调查结果
					voteSurveyResultServiceImpl.deleteEntity(surveyResult);
					
					if(isDel != 0) {
						delUserCount++;
					}
			 }
				//判断是否删除成功
				if(delUserCount == isDelFinish){
					noFlag++;
				}else{
					noFlag = -1;
				}
		     }
		  }
		  if(noFlag==nocheckedDepartIdLength){
				return 1; 
			 } else{
				return 0;
			 }
	}
   
	/**
	 * 将checkbox选中的用户添加到新增问卷发布用户中
	 */
	public int insertDeptUser(String surveyId, String checkedDepartIds){
		String[] checkedDepartIdArray = checkedDepartIds.split(",");
		int checkedDepartIdLength = checkedDepartIdArray.length;
		int flag = 0;
		SurveyUserEntity surveyUser = null;
		 
		  //查询checkbox状态从不选变为选中的用户
		  for( int n=0; n<checkedDepartIdArray.length; n++){
			  String checkedDepartId = checkedDepartIdArray[n];
			  surveyUser = new SurveyUserEntity();
			  surveyUser.setDept_id(checkedDepartId);
			  surveyUser.setSurvey_id(surveyId);
			  
			   // 新增问卷发布的对象用户
			  List<SurveyUserEntity> checkedUsernameArray = surveyReleaseMapper.getCheckedUser(surveyUser);
			  if(null != checkedUsernameArray){
				  
		    	//获取当前系统时间,为“创建时间”和“最后修改时间”属性赋值。
		    	String strToday =new SimpleDateFormat("yyyy-MM-dd").format(new Date());
		    	int isInsert = 0;
		    	//插入成功的条数
				int insertUserCount = 0;
		    	//选择的条数，用于验证是否添加成功
				int isDone = checkedUsernameArray.size();
				//遍历用户姓名数组
				for(int m = 0; m < checkedUsernameArray.size(); m++) {
					String checkedUsername = checkedUsernameArray.get(m).getUsername();
					
					//取到的用户名为空，跳出本次循环
					if(checkedUsername.equals("")) {
						isDone--;
						continue;
					}

					surveyUser.setCreate_time(strToday);
					surveyUser.setUsername(checkedUsername);
					surveyUser.setLast_modify_time(strToday);
					
					//添加用户
					isInsert = this.insertEntity(surveyUser);
					
					if(isInsert != 0) {
						insertUserCount++;
					}
				}

				if(insertUserCount == isDone){
					//添加成功的个数与姓名数组的长度一致，即为成功
					flag++;
				}else{
					flag = -1;
				}
		     }
		  }
		  
		  if(flag==checkedDepartIdLength){
				return 1; 
			 } else{
				return 0;
			 } 
	}

	/**
     * 删除用户对特定调查问卷的权限
     * @param survey_id
     * @param usernames
     * @return
     */
    public int deleteUser(String survey_id, String usernames) {
    	//把接收到的用户名字符串转化为数组
		String[] usernameArray = null;
		String username = "";
		int delUserCount = 0;
		usernameArray = usernames.split(",");
		
		//选择的条数，用于验证是否删除成功
		int isDelFinish = usernameArray.length;
		
		//遍历用户姓名数组
		for(int i = 0; i < usernameArray.length; i++) {
			username = usernameArray[i];
			
			//取到的用户名为空，跳出本次循环
			if(username.equals("")) {
				isDelFinish--;
				continue;
			}
			
			SurveyUserEntity surveyUser = new SurveyUserEntity();
			surveyUser.setSurvey_id(survey_id);
			surveyUser.setUsername(username);
			int isDel = this.deleteEntity(surveyUser);
			
			//删除该用户的对此调查问卷的调查结果
			SurveyResultEntity surveyResult = new SurveyResultEntity();
			surveyResult.setUsername(username);
			surveyResult.setSurveyId(new String(survey_id));
			
			//删除用户的调查结果
			voteSurveyResultServiceImpl.deleteEntity(surveyResult);
			
			if(isDel != 0) {
				delUserCount++;
			}
		}

		//判断是否删除成功
		if(delUserCount == isDelFinish){
			return 1;
		}else{
			return 0;
		}
    }
    
    /**
     * 发布调查问卷
     * @param survey
     * @return
     */
    public int surveyRelease(SurveyEntity survey) {
    	//将问卷的状态从“0”转为“1”
		String status = "1";
		survey.setStatus(status);
		
		//问卷发布
		int isRelease = surveyManagementServiceImpl.updateEntity(survey);
		//判断是否发布成功
		if(isRelease==1){
			return 1;
		}else{
			return 0;
		}
    }
    
    /**
     * 新增问卷发布的对象用户
     * @param groupForInsert
     * @param create_user 
     * @param survey_id
     * @param surveyUser
     * @return
     */
    
    @Override
	public int insertGroupUserToSurveyUserList(String groupForInsert, String survey_id,
			String create_user) {
    	//获取当前系统时间,为“创建时间”和“最后修改时间”属性赋值。
    	String strToday =new SimpleDateFormat("yyyy-MM-dd").format(new Date());
    	//把接收到的用户名字符串转化为数组
 		String[] groupIdArray;
		String groupId = "";
		int isInsert = 0;
		//插入成功的条数
		int insertGroupCount = 0;
		//插入成功的成员数
		int insertUserCount  = 0;
		SurveyUserEntity surveyUser = new SurveyUserEntity();
 		String is_join = "N";
 		
		//将接收到的用户姓名字符串按"，"分割开
		groupIdArray = groupForInsert.split(",");
				
		int insertGroupSize = groupIdArray.length;
		surveyUser.setIs_join(is_join);
		
		//遍历用户姓名数组
		for(int i = 0; i < groupIdArray.length; i++) {
			groupId = groupIdArray[i];
			
			surveyUser.setCreate_time(strToday);
			surveyUser.setLast_modify_time(strToday);
			surveyUser.setSurvey_id(survey_id);
			surveyUser.setCreate_user(create_user);
			surveyUser.setLast_modify_user(create_user);
			surveyUser.setGroup_id(groupId);
			
			//查询此组下未参与此问卷的用户
			List<SurveyUserEntity> insertGroups = surveyReleaseMapper.selectUserExistInSurvey(surveyUser);
			
			if(insertGroups.size() > 0){
					  for (int j = 0; j < insertGroups.size(); j++) {
						surveyUser.setUsername(insertGroups.get(j).getUsername());
						isInsert = surveyReleaseMapper.insertEntity(surveyUser);
						insertUserCount++;
					  }
					  if(isInsert > 0){
						  insertGroupCount++;
					  }
			    }else{
			    	insertGroupSize--;
			    }
			}
		
		if( insertGroupCount == insertGroupSize ){
			return insertUserCount;
		}else{
			return 0;
		}
	}
    
    /**
     * 删除问卷发布的对象用户
     * @param groupForDelete
     * @param survey_id
     * @param surveyUser
     * @return
     */
    public int deleteGroupUserToSurveyUserList(String groupForDelete,
			String survey_id) {
    	//把接收到的组名符串转化为数组
		String[] groupIdArray;
		SurveyUserEntity surveyUser = new SurveyUserEntity();
		String groupId = "";
		int delUserCount = 0;
		int deleteGroupCount = 0;
		int isDel = 0;
		groupIdArray  = groupForDelete.split(",");
		
		String is_join = "Y";
		
		int deleteGroupSize = groupIdArray.length;
		SurveyResultEntity surveyResult = new SurveyResultEntity();
		List<SurveyUserEntity> deleteGroups;
		
         //遍历组
		if(deleteGroupSize > 0){
			for(int i = 0; i < groupIdArray.length; i++) {
				groupId = groupIdArray[i];
				
				surveyUser.setGroup_id(groupId);
				surveyUser.setIs_join(is_join);
				surveyUser.setSurvey_id(survey_id.toString());
				//查询此组下参与此问卷的用户
				 deleteGroups = surveyReleaseMapper.selectUserExistInSurvey(surveyUser);
				
				 for (int j = 0; j < deleteGroups.size(); j++) {
					//删除此问卷下的成员信息
					surveyUser.setUsername(deleteGroups.get(j).getUsername());
					surveyUser.setSurvey_id(survey_id.toString());
					isDel = surveyReleaseMapper.deleteEntity(surveyUser);
					
					//删除此问卷结果的成员信息
					surveyResult.setUsername(deleteGroups.get(j).getUsername());
					surveyResult.setSurveyId(new String(survey_id));
					voteSurveyResultServiceImpl.deleteEntity(surveyResult);
					if(isDel > 0)
					delUserCount++;
					else
					deleteGroupSize--;
				 }
			}
			deleteGroupCount++;
		}
		//判断是否删除成功
		if( deleteGroupSize == deleteGroupCount){
			return delUserCount;
		}else{
			return 0;
		}
    }
    
    /**
   	 * 查询group人员投票权限状态
   	 * @param createUser
   	 * @param surveyId
   	 * @param map
   	 * @return
   	 */
   	@SuppressWarnings({ "unchecked", "rawtypes" })
	public List<SurveyUserEntity> selectGroupList(String  createUser,String surveyId) {
   		 
   		Map map = new HashMap();
   		map.put("createUser", createUser);
   	    QueryParam  queryParam= new QueryParam();
   	    queryParam.setQueryCondition(map);
   	    
   		List<SurveyUserEntity> groupList = surveyReleaseMapper.queryList( queryParam );
   		
   		String checkStatus ;
   		String group_id;
  
   		int joinedUserCount;
   		int allUserCount ;
   		SurveyUserEntity listForCheck = new SurveyUserEntity();
   		
   		for (int i = 0; i < groupList.size(); i++) {
   			
            group_id = groupList.get(i).getGroup_id().toString();
          
   			listForCheck.setSurvey_id(surveyId);
   			listForCheck.setGroup_id(group_id);
   			
   			//查询组内所有用户数量
   			 allUserCount   = surveyReleaseMapper.queryGroupUsersListAll(listForCheck);
   			//当组内用户数量大于0时,查询组内参与投票的用户
   			joinedUserCount = surveyReleaseMapper.queryGroupUsersListY(listForCheck);
   			
   			if(allUserCount == 0 || joinedUserCount ==0){
   			 checkStatus = "N";
   			}else if(allUserCount == joinedUserCount){
   				checkStatus = "A";
   			}else{
   				checkStatus = "H";}
   			
   			groupList.get(i).setCheckStatus(checkStatus);
   		}
   		
   		return groupList;
   	}
    
}
